import http from 'wechat-http'
// 1. 设置全局默认请求地址
http.baseURL = 'https://live-api.itheima.net/'
// 1. 设置请求拦截器
http.intercept.request = (config) => {
  config.header = {
    Authorization: 'Bearer ' + wx.getStorageSync('token'),
    ...config.header,
  }
  return config
}

// 2. 设置响应拦截器
http.intercept.response = async (res) => {
  if (res.data.code === 10000) {
    return res.data
  }
  else if (res.data.code === 401) {
    // console.log(res.config);
    const app = getApp()
    // 如果refreshToken也过期 
    if (res.config.url.includes('/refreshToken')) {
      // 清空本地两个token
      app.setToken('token', '')
      app.setToken('refreshToken', '')
      // 获取当前页面数组 用来跳转登陆后页面
      const pages = getCurrentPages()
      // 获取当前页面实例
      const page = pages[pages.length - 1]
      // 跳转登陆页
      wx.redirectTo({
        url: '/pages/login/index?redirectUrl=/' + page.route,
      })
      return
    }

    // 根据refreshToken 重发请求获取新token
    const nres = await http.post('/refreshToken', {}, {
      header: {
        Authorization: 'Bearer ' + wx.getStorageSync('refreshToken'),
      }
    })
    console.log(nres);
    // 存储返回的新的两个token
    app.setToken('token', nres.data.token)
    app.setToken('refreshToken', nres.data.refreshToken)
    // 重发请求
    res.config.header = {
      Authorization: 'Bearer ' + wx.getStorageSync('token')
    }
    return http(res.config)
  }
  else {
    wx.utils.toast(res.data.message || '业务错误')
    return Promise.reject(res.data)
  }

}
//
// 3. 导出
export default http